﻿
//已提取到对应的AREAS _PartialMain.js中
//function LoginOut() {}

//已提取到对应的AREAS _PartialMain.js中
//function LoginDialog() { }


//AJAX封装，不处理弹框业务(当前后面弹框会覆盖前一次弹框)
$.ajaxC = function (option) {
    $.ajax({
        type: option.type || "POST",
        url: option.url,
        data: option.data,
        dataType: option.dataType || "json",
        success: function (data) {
            if (ajaxDone(data)) {
                if (option.success) option.success(data);
            } else {
                if (option.error) option.error(data);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var data = new Object();
            data.message = data.message || "AJAX请求失败！";
            if (option.error) option.error(data);
            else msgerr(data);
        },
        complete: function () {
            if (option.complete) option.complete();
        }
    });
};

//AJAX封装，不处理弹框业务(当前后面弹框会覆盖前一次弹框)
$.ajaxN = function (option) {
    $.ajax({
        type: option.type || "POST",
        url: option.url,
        data: option.data,
        dataType: option.dataType || "json",
        success: function (data) {
            var jsonData = typeof (data) == "string" ? $.parseJSON(htmlDecode(data)) : data;
            if (jsonData.statusCode.toString() == "200") {
                if (option.success) option.success(data);
                if (jsonData.HandelCode.toString() == "1") location.reload();
            } else {
                if (option.error) option.error(data);
                else msgerr(data);
            }
        },
        error: function (data) {
            data.message = data.message || "保存失败！";
            if (option.error) option.error(data);
            else msgerr(data);
        },
        complete: function () {
            if (option.complete) option.complete();
        }
    });
};


//FORM表单提交，  form对象，option参数
$.fn.PostForm = function (option) {
    PostForm($(this), option);
};

//FORM提交
function PostForm(form, option) {
    var flag = true;
    if (option.vfn) {
        flag = option.vfn();
    }
    if (flag) {
        var $form = $(form);
        $.ajax({
            type: $form.method || 'POST',
            url: $form.attr("action"),
            data: $form.serializeArray(),
            dataType: "json",
            cache: false,
            success: function (data) {
                if (ajaxDone(data)) {
                    option.success(data);
                } else {
                    option.error(data);
                }
            },
            error: function (data) {
                data.message = data.message || "保存失败！";
                if (option.error) option.error(data);
                else msgerr(data);
            },
            complete: function () {
                if (option.complete) option.complete();
            }
        });
    }
}

function showload(option) {
    // alert("等贷款");
    $("#ajaxLoading h2").html(option.message);
    $("#ajaxLoading").css({ opacity: "1", visibility: "visible" });
    //opacity: 1;
    //visibility: visible;
}
function hideload() {
    $("#ajaxLoading").css({ opacity: "0", visibility: "hidden" });
}

function msgclose(option) {
    // window.NotificationFx.dismiss();
}

function msgerr(option) {
    //option.layout = "bar";
    //option.effect = 'slidetop';
    //option.type = 'error';
    //option.message = "<div class='msgicon'><i class='fa fa-times'></i></div><div class='msgcontent'>" + option.message + "</div> ";

    option.title = "错误 ERROR";
    option.message = "<div class='alert alert-danger'><i class='fa fa-times-circle fa-fw fa-lg'></i>" + option.message + "</div>";
    msgbase(option);
}

function msgwar(option) {
    // alert("弹出警告框");
    //    option.layout = "bar";
    //    option.effect = 'slidetop';
    //    option.type = 'warning';


    option.title = "警告 WARNING";
    option.message = "<div class='alert alert-warning'><i class='fa fa-warning fa-fw fa-lg'></i>" + option.message + "</div>";
    msgbase(option);
}

function msginfo(option) {
    //    option.layout = "bar";
    //    option.effect = 'slidetop';
    //    option.type = 'notice'; //蓝色

    option.title = "提示 INFORMATION";
    option.message = "<div class='alert alert-info'><i class='fa fa-info-circle fa-fw fa-lg'></i>" + option.message + "</div>";
    option.hideFooter = true;
    option.autoHide = option.autoHide || 1500;
    msgbase(option);
}

function msgsuc(option) {
    //    option.layout = "bar";
    //    option.effect = 'slidetop';
    //    option.type = 'success';
    //    option.message = "<div class='msgicon'><i class='fa fa-check'></i></div><div class='msgcontent'>" + option.message + "</div> ";

    option.title = "成功 SUCCESS";
    option.message = "<div class='alert alert-success'><i class='fa fa-check-circle fa-fw fa-lg'></i>" + option.message + "</div>";
    option.hideFooter = true;
    option.autoHide = option.autoHide || 1500;
    msgbase(option);
}

function msgbase(option) {
    //    var notification = new NotificationFx({
    //        message: option.message,
    //        layout: option.layout || 'growl',//bar 定位左上角 growl 有边距
    //        effect: option.effect || 'jelly',   //slide
    //        type: option.type || 'error', // notice, warning, error or success
    //        ttl: option.ttl || 3000,//自动关闭时间
    //        onClose: function () {
    //
    //        }
    //    });
    //    notification.show();
    option.content = option.message;
    ShowDialog(option);

}

function confirm(option) {
    ShowDialog({
        title: option.title || "确认 CONFIRM",
        content: "<div class='alert alert-warning'><i class='fa fa-warning fa-fw fa-lg'></i>" + option.message + "</div>",
        yesfn: option.yesfn,
        yestxt: "确定",
        notxt: "取消",
        nofn: option.nofn
    });
}


//弹出框按钮状态切换 option：{id:弹框ID}  isLoading：true(显示过渡提示) || false(显示按钮)
function DialogLoading(option, isLoading) {
    var $obj = $("#modal-" + option.id, $("#modal-container"));
    if (isLoading) {
        var msg = option.message || '<i class="fa fa-refresh fa-spin"></i>&nbsp;正在提交数据，请稍后';
        $("[role='footer']", $obj).hide();
        $("[role='footerLoading']", $obj).html(msg).show();
    } else {
        $("[role='footer']", $obj).show();
        $("[role='footerLoading']", $obj).hide();
    }
}

function ShowDialog(option) {
    //如果没有设置ID，则自动生成ID
    var id = option.id || (new Date()).valueOf();
    option.id = id;
    option.title = option.title || "&nbsp;";
    //弹框父容器
    var $p = $("#modal-container");
    //加载弹出框对象
    $p.SetHtmlData(option);
    //当前弹框对象
    var $obj = $("#modal-" + id, $p);
    $obj.data("id", id);
    if (option.width) {
        // $obj.width(option.width);
        $(".modal-dialog", $obj).width(option.width);
        $obj.css({ "max-width": "initial" });
    }
    //是否隐藏底部
    if (option.hideFooter) {
        $(".modal-footer", $obj).hide();
    } else {
        //取消按钮
        var notxt = option.notxt || "关闭";
        $("[role='no']", $obj).html(notxt).click(function () {
            if (option.nofn) option.nofn();
            CloseDialog(id);
        });

        //不设置确定按钮文本，则隐藏确定按钮
        if (option.yestxt) {
            var yestxt = option.yestxt;
            $("[role='yes']", $obj).html(yestxt).click(function () {
                if (option.yesfn) option.yesfn();
                //TODO 手动调用 CloseDialog 关闭弹框
            });
        } else {
            $("[role='yes']", $obj).hide();
        }
    }

    //如果内容加载高度超过当前屏幕，这自动加载滚动条
    $(".modal-body", $obj).resize(function () {
        var elem = $(this);
        var maxHeight = $(window).height() - 200;
        if (elem.height() >= maxHeight) {
            // $obj.css({ "position": "absolute", "top": "60%" });
            $obj.css({ "position": "absolute" });
        } else {
            // $obj.css({ "position": "fixed", "top": "50%" });
        }
    });

    //如果需要URL异步加载页面
    if (option.url) {
        DialogLoading({ id: id, message: '<i class="fa fa-refresh fa-spin"></i>&nbsp;页面正在加载，请稍后' }, true);

        $(".modal-body", $obj).load(option.url, function (data, status, xhr) {
            if (status == "success") {
                if (!ajaxDone(data)) {
                    //页面异常
                    CloseDialog(id);
                }
            } else {
                //请求失败
                CloseDialog(id);
                msgerr({ message: xhr.status + " " + xhr.statusText });
            }
            DialogLoading({ id: id }, false);
        });
    } else {
        $(".modal-body", $obj).html(option.content).append("<div class='clearfix'></div>");
    }
    zindex += 1;
    //设置ZINDEX
    $obj.css({ "z-index": zindex + 1 });
    $obj.next(".md-overlay").css({ "z-index": zindex, "opacity": 1, "visibility": "visible" });

    //加载动画
    // setTimeout(function () { $obj.addClass("md-show"); }, 100);
    //加载动画
    setTimeout(function () {
        $obj.addClass("in");
        $obj.show();
    }, 100);

    if (option.autoHide) {
        var time = setTimeout(function () {
            CloseDialog(id);
            clearTimeout(time);
        }, option.autoHide);
    }
}

var zindex = 1000;


//关闭弹窗（窗口ID，没有ID则关闭最后一个窗口）
function CloseDialog(id) {
    id = id || $("#modal-container .modal:last").data("id");
    $("#modal-" + id).removeClass("md-show");
    setTimeout(function () {
        $("#modal-" + id).remove();
        $("#modal-" + id + "-overlay").remove();
    }, 100);
}

//调用 $("#xxx").SetHtmlData(data, key);
$.fn.SetHtmlData = function (data, key) { SetHtmlData(data, $(this), key); };
//data 为json.Attr或者任意JSON格式
//obj 为容器对象 所有拼接的HTML都将放入这个容器中
//HTML中 字段用 {字段名} 来占位。字段名与JSON中一致，则会自动替换。
//容器中 放置一个 class="copyitem" 的隐藏层，用于存放原始HTML
function SetHtmlData(data, obj, key) {
    //原始HTML，用于替换的隐藏HTML
    var initHtml = $(".copyitem", obj).html().replace("fordel", "delete");
    var len = data.length;
    if (len > 0) {
        for (var i = 0; i < len; i++) {
            var model = data[i];
            obj.append(_SetHtmlDataAction(model, initHtml, key));
        }
    } else {
        obj.append(_SetHtmlDataAction(data, initHtml, key));
    }
    //参考HTML   
    //<ul id="order_lastbuy" class="checklist orderinfo">
    //    <div id="forLiCopy" class="copyitem" style="display: none">
    //        <li data-id="{guid}">{name}</li>
    //    </div>
    //</ul>
}
function _SetHtmlDataAction(data, html, key) {
    var colArr = Object.keys(data);
    for (var j = 0; j < colArr.length; j++) {
        var colName = colArr[j];
        var seed = key == colName ? ("_" + (new Date()).valueOf()) : "";
        var rex = new RegExp("{" + colName + "}", 'g');
        html = html.replace(rex, data[colName] + seed);
    }
    html = html.replace("{data-obj}", escape(JSON.stringify(data)));
    return html;
}


//处理AJAX返回结果
function ajaxDone(data) {
    var flag = true;
    try {
        var jsonData = typeof (data) == "string" ? $.parseJSON(htmlDecode(data)) : data;
        switch (jsonData.statusCode.toString()) {
            case "301":
                flag = false;
                LoginDialog(jsonData.message);
                break;
            case "300":
                flag = false;
                msgerr({ message: jsonData.message });
                break;
            case "200":
                flag = true;
                if (jsonData.HandelCode.toString() == "1") location.reload();
                break;
            case "400":
                flag = false;
                msgwar({ message: jsonData.message });
                break;
            default:
                break;
        }
    } catch (e) {
        flag = true;
    }
    return flag;
}

//html代码转异
function htmlDecode(str) {
    str = str.replace(/&amp;/gi, "&");
    str = str.replace(/&nbsp;/gi, " ");
    str = str.replace(/&quot;/gi, "\"");
    str = str.replace(/&#39;/g, "'");
    str = str.replace(/&lt;/gi, "<");
    str = str.replace(/&gt;/gi, ">");
    return str;
}